<?php
declare (strict_types = 1);
// +----------------------------------------------------------------------
// | 支付回调
// +----------------------------------------------------------------------

namespace app\home\controller;

use app\BaseController;
use app\common\model\Payment;
use app\common\model\User;
use app\common\model\UserBalanceLog;


class NotifyController extends BaseController
{
    /**
     * 支付通知
     */
    public function alipay()
    {
        $data         = $this->request->param();

        // 验证签名
        $verifyNotify = Payment::alipay()->verifyNotify($data);
        if (!$verifyNotify) {
            echo "fail";exit;
        }

        /**
         * 验签通过后实现业务逻辑
         * ①验签通过后核实如下参数out_trade_no、total_amount、seller_id
         * ②修改订单表 支付状态
         */
        if ($data['trade_status'] == 'TRADE_SUCCESS') {
            $this->handle($data['out_trade_no'], $data);
        }
        echo 'success';exit;//这个必须返回给支付宝，响应个支付宝，必须保证本界面无错误。只打印了success，否则支付宝将重复请求回调地址。
    }

    /**
     * 支付通知
     */
    public function wxpay()
    {
        $header = $this->request->header();
        $body   = file_get_contents("php://input");
        $pay    = Payment::wxpay();

        // 验证签名
        $verifyNotify = $pay->verifyNotify(compact('header', 'body'));
        if (!$verifyNotify) {
            return json(['code' => "ERROR", "message" => "失败"]);
        }
        /**
         * 验签通过后实现业务逻辑
         * ①验签通过后核实如下参数out_trade_no、total_fee、openid
         * ②修改订单表 支付状态
         **/
        $body = json_decode($body, true);
        if ($body['event_type'] == 'TRANSACTION.SUCCESS') {
            $resource = $pay->decryptToString($body['resource']['associated_data'], $body['resource']['nonce'], $body['resource']['ciphertext']);
            $resource = json_decode($resource, true);
            // 通知类型:支付通知
            if ($resource['trade_state'] == 'SUCCESS') {
                $this->handle($resource['out_trade_no'], $body);

                // 用户微信绑定openid
                //$openid = $resource['payer']['openid'];
            }

            // 通知类型:退款通知
            if ($resource['trade_state'] == 'REFUND.SUCCESS') {
                UserBalanceLog::where('out_trade_no', $resource['out_trade_no'])->update(['admin_note' => 'SUCCESS']);
            }
        }
        //通知应答
        return json(['code' => "SUCCESS", "message" => "成功"]);
    }

    public function handle($out_trade_no, $param = '')
    {
        trace($param, 'info');

        // 2.用户余额
        User::sysnChange($out_trade_no);
        return true;
    }
}